package connectionpool;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 */
public class HikariExecutor {
    
    private HikariConfig config;
    
    private HikariDataSource dataSource;
    
    public HikariDataSource getDataSource() {
        return dataSource;
    }
    
    public HikariExecutor(String url, String username, String password) throws SQLException {
        config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setPoolName("HikariCP connection pool");
        config.setUsername(username);
        config.setPassword(password);
        config.setMaximumPoolSize(1000);
        config.setMinimumIdle(100);
        dataSource = new HikariDataSource(config);
    }
    
    public HikariExecutor(String url, String username, String password, int minIdle, int maxSize) throws SQLException {
        config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setPoolName("HikariCP connection pool");
        config.setUsername(username);
        config.setPassword(password);
        config.setMaximumPoolSize(maxSize);
        config.setMinimumIdle(minIdle);
        dataSource = new HikariDataSource(config);
    }
    
    public void executeSQL(String sql) throws SQLException {
        try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) {
            System.err.println(sql);
            printResultSet(resultSet);
        }
    }
    
    private void printResultSet(ResultSet resultSet) throws  SQLException {
        ResultSetMetaData rsmd = resultSet.getMetaData();
        int columnsNumber = rsmd.getColumnCount();
        while (resultSet.next()) {
            for (int i = 1; i <= columnsNumber; i++) {
                if (i > 1) {
                    System.err.println(", ");
                }
                String columnValue = resultSet.getString(i);
                System.err.print(columnValue + " " + rsmd.getColumnName(i));
            }
            System.err.println("");
        }
    }
    
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public void close() {
        dataSource.close();
    }
}
